/*
 * Created on Nov 2, 2004
 *
 * To change the template for this generated file go to
 * Window&gt;Preferences&gt;Java&gt;Code Generation&gt;Code and Comments
 */
package com.erclab.internal.xpresso.formelements;

import java.io.ByteArrayInputStream;
import java.util.Properties;

import com.erclab.internal.xpresso.forms.Form;


/**
 * @author rodrigen
 *
 */
public class CheckBox extends SimpleTextDisplay {


	protected boolean isCheckedByDefault() {
		if(this.parameters == null || this.parameters.equals(""))
			return false;
		
		Properties props = new Properties();
		byte[] bytes = this.parameters.getBytes();

		ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
		try {
			props.load(bais);
		} catch (Exception ex){
			// TODO: Log this exception AS ERROR.
		}
		
		if(props.getProperty("checked") != null && props.getProperty("checked").equalsIgnoreCase("Y")){
			return true;
		}
		return false;
	}

	/* (non-Javadoc)
	 * @see com.erclab.internal.xpresso.formelements.FormElement#toHTML(com.erclab.internal.xpresso.forms.Form, com.erclab.internal.xpresso.forms.FormParameters)
	 */
	public String toHTML(Form theForm) {
		// TODO Auto-generated method stub
		StringBuffer sb = new StringBuffer();
		sb.append("<input name=\"Field" + this.idFormElement + "\"");
		sb.append(" type=\"checkbox\" id=\"Field" + this.idFormElement + "\" class=\"GenericCheckBox\" value=\"1\"");
		if(isChecked(theForm) ){
			sb.append(" checked");
		}
		sb.append(">");
		return sb.toString();
	}
	private boolean isChecked(Form theForm) {
		return (originalValue != null && originalValue.equals("1")) || 
				(isCheckedByDefault() && theForm.getFormParameters().getAction().equalsIgnoreCase("insert") ||
				(lookupValue != null && lookupValue.equals("1") && theForm.getFormParameters().getAction().equals("insert")));
	}

	/* (non-Javadoc)
	 * @see com.erclab.internal.xpresso.formelements.FormElement#isModifiable()
	 */
	public boolean isModifiable() {
		return true;
	}

	/* (non-Javadoc)
	 * @see com.erclab.internal.xpresso.formelements.FormElement#processSubmittedValues(java.lang.String[])
	 */
	public String[] processSubmittedValues(Form theForm, String[] submittedValues) {
		if(submittedValues != null && submittedValues.length > 0 && submittedValues[0] != null && !submittedValues[0].equals("")){
			return submittedValues;
		} else{
			return new String[]{"0"};
		}
	}

}
